﻿/*----------------------------------------------------------------------------------------
*
*  Copyright 2019, Gao Hai Hui, <fromzeropoint@126.com>.  All rights reserved.
*  https://gitee.com/helloworldghh/xoskit.git
*  Use of this source code is governed by a MIT license
*  that can be found in the License file.
*
----------------------------------------------------------------------------------------*/
#ifndef __XOSKIT_XOS_CORE_XOS_STL_SRC_TOOLS_AUTO_REF_H__
#define __XOSKIT_XOS_CORE_XOS_STL_SRC_TOOLS_AUTO_REF_H__

namespace xos_stl
{

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // auto_ref

    template< class T >
    class auto_ref
    {
    public:
		auto_ref( T * pT, int nNum )
		{
			m_bIsAdded = false;
			m_nRefNum = nNum;
			m_pT = pT;
			int ret = m_pT->add_ref( m_nRefNum );
			if( 0 == ret )
			{
				m_bIsAdded = true;
			}
		}
		~auto_ref()
		{
			if( m_bIsAdded )
			{
				m_pT->sub_ref( m_nRefNum );
			}
			m_bIsAdded = false;
			m_nRefNum = 0;
			m_pT = 0;
		}
	public:
		int is_added()
		{
			int ret = 0;
			if( !m_bIsAdded )
			{
				ret = 1;
			}
			return ret;
		}
	protected:
		bool m_bIsAdded;
		int m_nRefNum;
		T * m_pT;
    };

} // xos_stl

#endif // __XOSKIT_XOS_CORE_XOS_STL_SRC_TOOLS_AUTO_REF_H__
